package com.idroid.utils;

import android.os.AsyncTask;
import android.util.Log;

import com.squareup.okhttp.DownLoadCallback;
import com.squareup.okhttp.OkHttp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Response;

/**
 * 网络缓存的工具类
 */
public class NetCacheUtils {


    public NetCacheUtils() {

    }


    public void getBitmapFromNet(String url, File file) {
        MyAsyncTask task = new MyAsyncTask();
        task.execute(url, file);
    }

    /**
     * 第一个泛型--异步任务执行的时候，通过execute传过来的参数； 第二个泛型--更新进度； 第三个泛型--异步任务执行以后返回的结果
     */
    private class MyAsyncTask extends AsyncTask<Object, Void, Boolean> {
        boolean isSave = false;

        // 耗时任务执行之前 --主线程
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        // 后台执行的任务
        @Override
        protected Boolean doInBackground(final Object... params) {
            // 执行异步任务的时候，将URL传过来

            try {
                String url = (String) params[0];
                OkHttp.downloadFileFromUrl(url, new DownLoadCallback.DownLoadCallBackListener() {
                    @Override
                    public void onResponse(Response response) {
                        isSave = saveFile2Local(response, (File) params[1]);
                    }

                    @Override
                    public void onFailure(int ErrorCode, String msg) {
                        Log.e("Download File Error:", msg);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }


            return isSave;
        }

        // 更新进度 --主线程
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        // 耗时任务执行之后--主线程
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPreExecute();
        }
    }

    /**
     * 保存文件
     *
     * @param response
     * @param file
     */
    private Boolean saveFile2Local(Response response, File file) {

        InputStream inputStream = null;
        OutputStream output = null;

        try {
            if (response.code() != 200) {
                file.delete();
                return false;
            }

            inputStream = response.body().byteStream();
            output = new FileOutputStream(file);
            byte[] buff = new byte[1024 * 4];
            while (true) {
                int readed = inputStream.read(buff);
                if (readed == -1) {
                    break;
                }
                output.write(buff, 0, readed);
            }
            output.flush();
            return true;
        } catch (IOException e) {
            file.delete();
            file = null;
            e.printStackTrace();
            return false;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
